package com.network.proxy;

import com.network.proxy.annotation.Get;
import com.network.proxy.annotation.Query;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by kkmike999 on 2016/06/04.
 */
public class ServiceMethod {
	protected Method         method;
	protected Annotation[]   methodAnnotations;
	protected Annotation[][] argumentAnnotations;
	protected Class[]        argumentTypes;
	protected Type           returnType;
	/** json convert类型 */
	protected Type           actualType;// Obserable<?> HttpCall<?> 里面的type

	public ServiceMethod(Method method) {
		this.method = method;

		methodAnnotations = method.getDeclaredAnnotations();
		argumentAnnotations = method.getParameterAnnotations();
		argumentTypes = method.getParameterTypes();
		returnType = method.getGenericReturnType();

		if (returnType instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) returnType;

			actualType = parameterizedType.getActualTypeArguments()[0];
		} else {
			actualType = returnType;
		}
	}

	public String getQueryKey(int index) {
		for (Annotation annotation : argumentAnnotations[index]) {
			if (annotation instanceof Query) {
				return ((Query) annotation).value();
			}
		}

		return "";
	}

	public String url() {
		for (Annotation annotation : methodAnnotations) {
			if (annotation instanceof Get) {
				String url = ((Get) annotation).value();
				return url;
			}
		}

		throw new RuntimeException("no GET or POST annotation");
	}
}
